<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { marked } from 'marked'
import { apiClient } from '@/utils/api'

// 消息接口类型定义
interface Message {
  id: string
  content: string
  role: 'user' | 'assistant'
  timestamp: Date | string
  isLoading?: boolean
}

// AI配置接口类型定义
interface AiConfig {
  id?: string
  name: string
  provider: string
  model: string
  apiUrl: string
  apiKey: string
  description?: string
  parameters: {
    temperature: number
    maxTokens: number
    topP?: number
  }
  isDefault?: boolean
  isActive?: boolean
  createdAt?: string | Date
  updatedAt?: string | Date
}

const authStore = useAuthStore()

// 聊天相关状态
const messages = ref<Message[]>([])
const currentMessage = ref('')
const isLoading = ref(false)
const chatContainer = ref<HTMLElement>()

// 历史对话记录
const chatHistory = ref<Array<{
  id: string
  title: string
  timestamp: Date
  messages: Message[]
  sessionId?: string // 数据库会话ID
}>>([])  

const currentChatId = ref('')
const currentSessionId = ref<string | null>(null) // 当前数据库会话ID

// 搜索和筛选相关状态
const searchQuery = ref('')
const selectedChatType = ref('')

// AI配置相关状态
const aiConfigs = ref<AiConfig[]>([])
const currentAiConfig = ref<AiConfig | null>(null)
const showApiConfig = ref(false)
const isLoadingConfig = ref(false)

// 新建/编辑配置表单
const configForm = ref<AiConfig>({
  name: '',
  provider: 'siliconflow',
  model: 'deepseek-ai/DeepSeek-V2.5',
  apiUrl: 'https://api.siliconflow.cn/v1',
  apiKey: '',
  description: '',
  parameters: {
    temperature: 0.7,
    maxTokens: 2000
  }
})

const editingConfigId = ref<string | null>(null)
const showConfigForm = ref(false)

// 计算属性
const isAdmin = computed(() => authStore.user?.role === 'admin')
const currentChat = computed(() => 
  chatHistory.value.find(chat => chat.id === currentChatId.value)
)

// 筛选后的对话历史
const filteredChatHistory = computed(() => {
  let filtered = chatHistory.value
  
  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim()
    filtered = filtered.filter(chat => 
      chat.title.toLowerCase().includes(query) ||
      chat.messages.some(msg => msg.content.toLowerCase().includes(query))
    )
  }
  
  // 按会话类型筛选
  if (selectedChatType.value) {
    if (selectedChatType.value === 'local') {
      filtered = filtered.filter(chat => !chat.sessionId)
    } else if (selectedChatType.value === 'database') {
      filtered = filtered.filter(chat => chat.sessionId)
    }
  }
  
  return filtered
})

// 加载AI配置列表
const loadAiConfigs = async () => {
  if (!authStore.isAuthenticated) {
    console.log('用户未认证，跳过加载AI配置列表')
    return
  }
  
  try {
    isLoadingConfig.value = true
    const response = await apiClient.get('/api/ai-config')
    // 后端返回格式: {success: true, data: {count, rows}}
    aiConfigs.value = response.data.data?.rows || []
    console.log('成功加载AI配置列表:', aiConfigs.value)
  } catch (error) {
    console.error('加载AI配置失败:', error)
  } finally {
    isLoadingConfig.value = false
  }
}

// 加载默认AI配置
const loadDefaultConfig = async () => {
  try {
    const response = await apiClient.get('/api/ai-config/default/config')
    currentAiConfig.value = response.data.data.config
    console.log('成功加载默认配置:', response.data.data.config)
  } catch (error:any) {
    console.error('加载默认配置失败:', error.response?.data?.error?.message || error.message)
    // 如果没有默认配置，使用本地存储的配置作为后备
    currentAiConfig.value = {
      name: '默认配置',
      provider: 'siliconflow',
      apiKey: localStorage.getItem('kb_api_key') || '',
      apiUrl: localStorage.getItem('kb_base_url') || 'https://api.siliconflow.cn/v1',
      model: localStorage.getItem('kb_model') || 'deepseek-ai/DeepSeek-V2.5',
      parameters: {
        temperature: 0.7,
        maxTokens: 2000
      }
    }
    console.log('使用本地后备配置:', currentAiConfig.value)
  }
}

// 创建或更新AI配置
const saveAiConfig = async () => {
  try {
    isLoadingConfig.value = true
    
    if (editingConfigId.value) {
      // 更新配置
      await apiClient.put(`/api/ai-config/${editingConfigId.value}`, configForm.value)
    } else {
      // 创建新配置
      await apiClient.post('/api/ai-config', configForm.value)
    }
    
    showConfigForm.value = false
    resetConfigForm()
    if (authStore.isAuthenticated) {
      await loadAiConfigs()
    }
    await loadDefaultConfig()
  } catch (error) {
    console.error('保存AI配置失败:', error)
    alert('保存配置失败，请检查网络连接')
  } finally {
    isLoadingConfig.value = false
  }
}

// 设置默认配置
const setDefaultConfig = async (configId: string) => {
  try {
    await apiClient.put(`/api/ai-config/${configId}/default`)
    await loadDefaultConfig()
    if (authStore.isAuthenticated) {
      await loadAiConfigs()
    }
  } catch (error) {
    console.error('设置默认配置失败:', error)
    alert('设置默认配置失败')
  }
}

// 删除配置
const deleteConfig = async (configId: string) => {
  if (!confirm('确定要删除这个配置吗？')) return
  
  try {
    await apiClient.delete(`/api/ai-config/${configId}`)
    if (authStore.isAuthenticated) {
      await loadAiConfigs()
    }
    await loadDefaultConfig()
  } catch (error) {
    console.error('删除配置失败:', error)
    alert('删除配置失败')
  }
}

// 重置配置表单
const resetConfigForm = () => {
  configForm.value = {
    name: '',
    provider: 'siliconflow',
    model: 'deepseek-ai/DeepSeek-V2.5',
    apiUrl: 'https://api.siliconflow.cn/v1',
    apiKey: '',
    description: '',
    parameters: {
      temperature: 0.7,
      maxTokens: 2000
    }
  }
  editingConfigId.value = null
}

// 编辑配置
const editConfig = (config: any) => {
  configForm.value = { ...config }
  editingConfigId.value = config.id
  showConfigForm.value = true
}

// 新建配置
const createNewConfig = () => {
  resetConfigForm()
  showConfigForm.value = true
}

// 创建新的数据库会话
const createDatabaseSession = async (title?: string) => {
  if (!authStore.isAuthenticated) {
    return null // 未登录用户不创建数据库会话
  }
  
  try {
    const response = await apiClient.post('/api/chat/sessions', {
      title: title || '新对话',
      aiConfigId: currentAiConfig.value?.id || null
    })
    return response.data.data.session
  } catch (error) {
    console.error('创建数据库会话失败:', error)
    return null
  }
}

// 发送消息到数据库
const sendMessageToDatabase = async (sessionId: string, content: string, role: 'user' | 'assistant') => {
  if (!authStore.isAuthenticated || !sessionId) {
    return null
  }
  
  try {
    const response = await apiClient.post(`/api/chat/sessions/${sessionId}/messages`, {
      content,
      role,
      aiConfigId: currentAiConfig.value?.id || null
    })
    console.log("发送消息到数据库", messages)
    return response.data.data
  } catch (error) {
    console.error('发送消息到数据库失败:', error)
    return null
  }
}

// 发送消息
const sendMessage = async () => {
  if (!currentMessage.value.trim() || isLoading.value) return
  
  const messageContent = currentMessage.value
  currentMessage.value = ''
  
  // 如果没有当前会话，先创建一个
  if (!currentSessionId.value && authStore.isAuthenticated) {
    const session = await createDatabaseSession()
    if (session) {
      currentSessionId.value = session.id
      // 更新当前聊天记录的sessionId
      const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
      if (currentChat) {
        currentChat.sessionId = session.id
      }
    }
  }
  
  const userMessage = {
    id: Date.now().toString(),
    content: messageContent,
    role: 'user' as const,
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)

  // 注释掉单独的用户消息保存，因为后端ChatService.sendMessage会处理消息保存
  // if (currentSessionId.value) {
  //   await sendMessageToDatabase(currentSessionId.value, messageContent, 'user')
  // }
  
  // 添加加载中的助手消息
  const loadingMessage = {
    id: (Date.now() + 1).toString(),
    content: '',
    role: 'assistant' as const,
    timestamp: new Date(),
    isLoading: true
  }
  messages.value.push(loadingMessage)

  isLoading.value = true

  try {
    await nextTick()
    scrollToBottom()
    
    if (!currentAiConfig.value || !currentAiConfig.value.apiKey) {
      throw new Error('请先配置API密钥')
    }
    
    // 调用后端ChatService.sendMessage接口，统一处理消息保存
    const response = await apiClient.post(`/api/chat/sessions/${currentSessionId.value}/messages`, {
      content: messageContent,
      role: 'user',
      aiConfigId: currentAiConfig.value?.id || null
    })
    
    const result = response.data.data
    const assistantMessage = result.assistantMessage?.content || '抱歉，我无法回答这个问题。'
    
    // 更新加载中的消息
    const loadingIndex = messages.value.findIndex(msg => msg.isLoading)
    if (loadingIndex !== -1) {
      messages.value[loadingIndex] = {
        ...loadingMessage,
        content: assistantMessage,
        isLoading: false
      }
    }
    
    // 助手消息已通过后端ChatService.sendMessage统一保存，无需单独调用
    // if (currentSessionId.value) {
    //   await sendMessageToDatabase(currentSessionId.value, assistantMessage, 'assistant')
    // }
    
  } catch (error) {
    console.error('发送消息失败:', error)
    // 更新加载中的消息为错误消息
    const loadingIndex = messages.value.findIndex(msg => msg.isLoading)
    if (loadingIndex !== -1) {
      const errorMessage = `抱歉，发生了错误: ${error instanceof Error ? error.message : '未知错误'}`
      messages.value[loadingIndex] = {
        ...loadingMessage,
        content: errorMessage,
        isLoading: false
      }
      
      // 发送错误消息到数据库
      if (currentSessionId.value) {
        await sendMessageToDatabase(currentSessionId.value, errorMessage, 'assistant')
      }
    }
  } finally {
    isLoading.value = false
    await nextTick()
    scrollToBottom()
    updateCurrentChat()
  }
  // messages.value.push(confirmMessage)
  
  // await nextTick()
  // scrollToBottom()
  // updateCurrentChat()
}

// 加载用户的数据库会话列表
const loadDatabaseSessions = async () => {
  if (!authStore.isAuthenticated) {
    return []
  }
  
  try {
    const response = await apiClient.get('/api/chat/sessions')
    return response.data.data.sessions || []
  } catch (error) {
    console.error('加载数据库会话失败:', error)
    return []
  }
}

// 加载特定会话的消息历史
const loadSessionMessages = async (sessionId: string) => {
  if (!authStore.isAuthenticated || !sessionId) {
    return []
  }
  
  try {
    const response = await apiClient.get(`/api/chat/sessions/${sessionId}/messages`)
    return response.data.data.data || []
  } catch (error) {
    console.error('加载会话消息失败:', error)
    return []
  }
}

// 从数据库会话创建聊天历史项
const createChatFromSession = (session: any) => {
  return {
    id: `session-${session.id}`,
    sessionId: session.id,
    title: session.title || '新对话',
    messages: [],
    timestamp: new Date(session.createdAt),
    aiConfig: session.aiConfigId ? aiConfigs.value.find(config => config.id === session.aiConfigId) : null
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 创建新对话
const createNewChat = () => {
  const newChat = {
    id: Date.now().toString(),
    sessionId: undefined, // 数据库会话ID，将在发送第一条消息时创建
    title: `对话 ${chatHistory.value.length + 1}`,
    timestamp: new Date(),
    messages: [{
      id: '1',
      content: '您好！我是前端知识库助手，可以帮助您解答前端开发相关的问题。请问有什么可以帮助您的吗？',
      role: 'assistant' as const,
      timestamp: new Date()
    }]
  }
  
  chatHistory.value.push(newChat)
  currentSessionId.value = null
  switchChat(newChat.id)
  saveChatHistory()
}

// 切换对话
const switchChat = async (chatId: string) => {
  updateCurrentChat()
  currentChatId.value = chatId
  const chat = chatHistory.value.find(c => c.id === chatId)
  if (chat) {
    currentSessionId.value = chat.sessionId ?? null
    
    // 如果是数据库会话，从数据库加载消息
    if (chat.sessionId && authStore.isAuthenticated) {
      try {
        const dbMessages = await loadSessionMessages(chat.sessionId)
        // 转换数据库消息格式
        const convertedMessages = dbMessages.map((msg: any) => ({
          id: msg.id.toString(),
          content: msg.content,
          role: msg.role,
          timestamp: new Date(msg.createdAt)
        }))
        // 按时间戳升序排序，确保消息按正确的时间顺序显示
        convertedMessages.sort((a: any, b: any) => a.timestamp.getTime() - b.timestamp.getTime())
        messages.value = convertedMessages
        chat.messages = convertedMessages // 更新本地缓存
      } catch (error) {
        console.error('加载会话消息失败:', error)
        messages.value = [...chat.messages] // 使用本地缓存
      }
    } else {
      messages.value = [...chat.messages]
    }
    
    nextTick(() => scrollToBottom())
  }
}

// 更新数据库会话标题
const updateDatabaseSessionTitle = async (sessionId: string, title: string) => {
  if (!authStore.isAuthenticated || !sessionId) {
    return false
  }
  
  try {
    await apiClient.put(`/api/chat/sessions/${sessionId}`, { title })
    return true
  } catch (error) {
    console.error('更新数据库会话标题失败:', error)
    return false
  }
}

// 重命名聊天
const renameChat = async (chatId: string) => {
  const chat = chatHistory.value.find(c => c.id === chatId)
  if (!chat) return
  
  const newTitle = prompt('请输入新的对话标题:', chat.title)
  if (!newTitle || newTitle.trim() === '' || newTitle === chat.title) {
    return
  }
  
  // 如果是数据库会话，更新数据库
  if (chat.sessionId) {
    const success = await updateDatabaseSessionTitle(chat.sessionId, newTitle.trim())
    if (!success) {
      alert('更新数据库会话标题失败')
      return
    }
  }
  
  // 更新本地标题
  chat.title = newTitle.trim()
  saveChatHistory()
}

// 更新当前对话
const updateCurrentChat = () => {
  const chatIndex = chatHistory.value.findIndex(chat => chat.id === currentChatId.value)
  if (chatIndex !== -1) {
    chatHistory.value[chatIndex].messages = [...messages.value]
    // 更新标题为第一条用户消息的前20个字符
    const firstUserMessage = messages.value.find(msg => msg.role === 'user')
    if (firstUserMessage && chatHistory.value[chatIndex].title.startsWith('对话')) {
      chatHistory.value[chatIndex].title = firstUserMessage.content.slice(0, 20) + (firstUserMessage.content.length > 20 ? '...' : '')
    }
    // 保存聊天历史
    saveChatHistory()
  }
}

// 删除数据库会话
const deleteDatabaseSession = async (sessionId: string) => {
  if (!authStore.isAuthenticated || !sessionId) {
    return false
  }
  
  try {
    await apiClient.delete(`/api/chat/sessions/${sessionId}`)
    return true
  } catch (error) {
    console.error('删除数据库会话失败:', error)
    return false
  }
}

// 删除对话
const deleteChat = async (chatId: string) => {
  if (chatHistory.value.length <= 1) return
  
  const chat = chatHistory.value.find(c => c.id === chatId)
  if (!chat) return
  
  // 如果是数据库会话，先删除数据库记录
  if (chat.sessionId) {
    const success = await deleteDatabaseSession(chat.sessionId)
    if (!success) {
      // 删除失败，询问用户是否只删除本地记录
      const confirmDelete = confirm('删除数据库会话失败，是否只删除本地记录？')
      if (!confirmDelete) {
        return
      }
    }
  }
  
  const index = chatHistory.value.findIndex(chat => chat.id === chatId)
  if (index !== -1) {
    chatHistory.value.splice(index, 1)
    if (currentChatId.value === chatId) {
      await switchChat(chatHistory.value[0].id)
    }
    saveChatHistory()
  }
}

// 清空当前对话
const clearCurrentChat = () => {
  messages.value = [{
    id: '1',
    content: '您好！我是前端知识库助手，可以帮助您解答前端开发相关的问题。请问有什么可以帮助您的吗？',
    role: 'assistant',
    timestamp: new Date()
  }]
  updateCurrentChat()
}



// 渲染Markdown
const renderMarkdown = (content: string) => {
  return marked(content)
}

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    // 如果用户已认证，优先从数据库加载
    if (authStore.isAuthenticated) {
      await loadChatHistoryFromDatabase()
    } else {
      // 未认证用户从本地存储加载
      loadChatHistoryFromLocal()
    }
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    // 如果加载失败，尝试从本地存储加载
    loadChatHistoryFromLocal()
  }
}

// 从数据库加载聊天历史
const loadChatHistoryFromDatabase = async () => {
  try {
    // 获取用户的会话列表
    const sessionsResponse = await apiClient.get('/api/chat/sessions')
    console.log('Sessions API响应:', sessionsResponse.data)
    const sessions = sessionsResponse.data.data.data || []
    
    // 确保sessions是数组
    if (!Array.isArray(sessions)) {
      console.warn('Sessions数据格式错误,不是数组:', sessions)
      return
    }
    
    // 为每个会话加载消息历史
    const chatHistoryData = []
    for (const session of sessions) {
      try {
        const messagesResponse = await apiClient.get(`/api/chat/sessions/${session.id}/messages`)
        const messages = messagesResponse.data.data.data || []
        console.log(messages)
        // 转换为前端格式
        const convertedMessages = messages.map((msg: any) => ({
          id: msg.id.toString(),
          content: msg.content,
          role: msg.role,
          timestamp: new Date(msg.createdAt)
        }))
        
        chatHistoryData.push({
          id: `session-${session.id}`,
          sessionId: session.id,
          title: session.title || '新对话',
          timestamp: new Date(session.createdAt),
          messages: convertedMessages
        })
      } catch (error) {
        console.error(`加载会话 ${session.id} 的消息失败:`, error)
        // 即使某个会话的消息加载失败，也要保留会话记录
        chatHistoryData.push({
          id: `session-${session.id}`,
          sessionId: session.id,
          title: session.title || '新对话',
          timestamp: new Date(session.createdAt),
          messages: []
        })
      }
    }
    
    // 按时间倒序排列（最新的在前面）
    chatHistory.value = chatHistoryData.sort((a, b) => 
      new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    )
    
    console.log('从数据库加载聊天历史成功:', chatHistory.value.length, '个会话')
    
    // 如果有会话，切换到最新的会话
    if (chatHistory.value.length > 0) {
      await switchChat(chatHistory.value[0].id)
    }
    
  } catch (error) {
    console.error('从数据库加载聊天历史失败:', error)
    throw error
  }
}

// 从本地存储加载聊天历史
const loadChatHistoryFromLocal = () => {
  try {
    const savedHistory = localStorage.getItem('kb_chat_history')
    if (savedHistory) {
      const parsedHistory = JSON.parse(savedHistory)
      if (Array.isArray(parsedHistory) && parsedHistory.length > 0) {
        // 恢复时间戳对象
        chatHistory.value = parsedHistory.map(chat => ({
          ...chat,
          timestamp: new Date(chat.timestamp),
          messages: chat.messages.map((msg: Message) => ({
            ...msg,
            timestamp: new Date(msg.timestamp)
          }))
        }))
        
        // 恢复当前对话
        const savedCurrentChatId = localStorage.getItem('kb_current_chat_id')
        if (savedCurrentChatId && chatHistory.value.find(chat => chat.id === savedCurrentChatId)) {
          switchChat(savedCurrentChatId)
        } else if (chatHistory.value.length > 0) {
          switchChat(chatHistory.value[0].id)
        }
      }
    }
  } catch (error) {
    console.error('从本地存储加载聊天历史失败:', error)
  }
}

// 保存聊天历史
const saveChatHistory = () => {
  try {
    localStorage.setItem('kb_chat_history', JSON.stringify(chatHistory.value))
    localStorage.setItem('kb_current_chat_id', currentChatId.value)
  } catch (error) {
    console.error('保存聊天历史失败:', error)
  }
}

// 处理回车发送
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 格式化时间显示
const formatTime = (timestamp: Date | string): string => {
  const date = timestamp instanceof Date ? timestamp : new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化数据库会话历史
const initializeDatabaseSessions = async () => {
  if (!authStore.isAuthenticated) {
    return
  }
  
  try {
    const sessions = await loadDatabaseSessions()
    
    // 将数据库会话转换为聊天历史格式并合并
    const sessionChats = sessions.map(createChatFromSession)
    
    // 合并本地聊天历史和数据库会话，去重
    const existingSessionIds = new Set(chatHistory.value.map(chat => chat.sessionId).filter(Boolean))
    const newSessionChats = sessionChats.filter((chat: { id: string; title: string; timestamp: Date; messages: Message[]; sessionId?: string }) => !existingSessionIds.has(chat.sessionId))
    
    if (newSessionChats.length > 0) {
      chatHistory.value = [...newSessionChats, ...chatHistory.value]
      saveChatHistory()
    }
  } catch (error) {
    console.error('初始化数据库会话失败:', error)
  }
}

// 组件挂载时初始化
onMounted(async () => {
  // 恢复认证状态
  authStore.restoreAuth()
  
  // 等待下一个tick确保认证状态完全恢复
  await nextTick()
  
  await loadChatHistory()
  
  // 总是加载默认配置（不需要认证）
  await loadDefaultConfig()
  
  // 检查是否已认证再调用需要认证的API
  if (authStore.isAuthenticated) {
    await loadAiConfigs()
  } else {
    console.warn('用户未认证,跳过加载AI配置列表')
  }
  
  // 如果没有聊天历史，创建一个新的
  if (chatHistory.value.length === 0) {
    createNewChat()
  }
  
  nextTick(() => scrollToBottom())
})

// 监听登录状态变化
watch(() => authStore.isAuthenticated, async (isAuthenticated) => {
  if (isAuthenticated) {
    // 用户登录后，重新加载聊天历史（从数据库）
    await loadChatHistory()
  } else {
    // 用户登出后，清除数据库会话相关的聊天历史
    chatHistory.value = chatHistory.value.filter(chat => !chat.sessionId)
    currentSessionId.value = null
    saveChatHistory()
    
    // 如果当前聊天是数据库会话，切换到本地聊天或创建新聊天
    const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
    if (!currentChat) {
      if (chatHistory.value.length > 0) {
        await switchChat(chatHistory.value[0].id)
      } else {
        createNewChat()
      }
    }
  }
})
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-screen flex">
      <!-- 侧边栏 - 对话历史 -->
      <div class="w-80 bg-white border-r border-gray-200 flex flex-col">
      <!-- 侧边栏头部 -->
      <div class="p-4 border-b border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold text-gray-900">前端知识库</h2>
          <button
            @click="createNewChat"
            class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            title="新建对话"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
          </button>
        </div>
        
        <!-- 认证状态提示 -->
        <div v-if="!authStore.isAuthenticated" class="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
          <div class="flex items-center">
            <svg class="w-4 h-4 text-yellow-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
            <span class="text-sm text-yellow-800">未登录状态，使用本地配置</span>
          </div>
          <router-link to="/login" class="text-xs text-yellow-700 hover:text-yellow-900 underline mt-1 block">
            点击登录获取完整功能
          </router-link>
        </div>
        
        <!-- 已登录用户信息 -->
        <div v-else class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <svg class="w-4 h-4 text-green-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span class="text-sm text-green-800">{{ authStore.user?.username || '已登录' }}</span>
            </div>
            <button @click="authStore.logout()" class="text-xs text-green-700 hover:text-green-900 underline">
              退出
            </button>
          </div>
        </div>
        
        <!-- 管理员AI配置管理 -->
        <div v-if="isAdmin" class="mb-2">
          <button
            @click="showApiConfig = true"
            class="w-full px-3 py-2 text-sm text-left text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            AI配置管理
          </button>
        </div>
      </div>
      
      <!-- 对话历史列表 -->
      <div class="flex-1 overflow-y-auto">
        <div class="p-2 space-y-1">
          <div
            v-for="chat in filteredChatHistory"
            :key="chat.id"
            class="group relative"
          >
            <button
              @click="switchChat(chat.id)"
              :class="[
                'w-full text-left p-3 rounded-lg transition-colors',
                currentChatId === chat.id
                  ? 'bg-blue-50 text-blue-900 border border-blue-200'
                  : 'text-gray-700 hover:bg-gray-100'
              ]"
            >
              <div class="flex items-center justify-between mb-1">
                <div class="font-medium text-sm truncate flex-1">{{ chat.title }}</div>
                <div class="flex items-center gap-1 ml-2">
                  <span v-if="chat.sessionId" class="px-1.5 py-0.5 bg-green-100 text-green-700 text-xs rounded" title="数据库会话">DB</span>
                  <span v-else class="px-1.5 py-0.5 bg-gray-100 text-gray-600 text-xs rounded" title="本地会话">本地</span>
                </div>
              </div>
              <div class="text-xs text-gray-500">{{ formatTime(chat.timestamp) }}</div>
            </button>
            
            <!-- 重命名按钮 -->
            <button
              @click="renameChat(chat.id)"
              class="absolute top-2 right-8 p-1 text-gray-400 hover:text-blue-500 opacity-0 group-hover:opacity-100 transition-opacity"
              title="重命名对话"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
              </svg>
            </button>
            
            <!-- 删除按钮 -->
            <button
              v-if="chatHistory.length > 1"
              @click="deleteChat(chat.id)"
              class="absolute top-2 right-2 p-1 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
              :title="chat.sessionId ? '删除数据库会话' : '删除本地对话'"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col " style="height: calc(100vh - 64px);overflow: hidden;">
      <!-- 聊天头部 -->
      <div class="bg-white border-b border-gray-200 py-4">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <!-- 页面标题 -->
          <div class="flex items-center justify-between mb-4">
            <div>
              <h3 class="text-lg font-semibold text-gray-900">{{ currentChat?.title || '前端知识库' }}</h3>
              <p class="text-sm text-gray-500">AI助手为您解答前端开发问题</p>
            </div>
          </div>
          
          <!-- 搜索和筛选栏 -->
          <div class="flex flex-wrap items-center gap-4 mb-4">
            <!-- 搜索框 -->
            <div class="flex-1 min-w-64">
              <div class="relative">
                <input
                  v-model="searchQuery"
                  type="text"
                  placeholder="搜索对话历史..."
                  class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
              </div>
            </div>
            
            <!-- 会话类型筛选 -->
            <div class="min-w-32">
              <select
                v-model="selectedChatType"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="">全部会话</option>
                <option value="local">本地会话</option>
                <option value="database">数据库会话</option>
              </select>
            </div>
            
            <!-- 操作按钮 -->
            <div class="flex items-center gap-2">
              <button
                @click="createNewChat"
                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
                title="新建对话"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                </svg>
                新建对话
              </button>
              
              <button
                @click="clearCurrentChat"
                class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
                title="清空当前对话"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
                清空对话
              </button>
              
              <button
                @click="loadChatHistory"
                class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
                title="刷新对话历史"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                刷新
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 消息列表 -->
      <div ref="chatContainer" class="flex-1 overflow-y-auto p-4">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-4">
          <div
            v-for="message in messages"
            :key="message.id"
            :class="[
              'flex',
              message.role === 'user' ? 'justify-end' : 'justify-start'
            ]"
          >
            <div
              :class="[
                'max-w-3xl px-4 py-3 rounded-lg',
                message.role === 'user'
                  ? 'bg-blue-600 text-white'
                  : 'bg-white border border-gray-200 text-gray-900'
              ]"
            >
              <div v-if="message.isLoading" class="flex items-center space-x-2">
                <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-600"></div>
                <span class="text-sm">思考中...</span>
              </div>
              <div v-else-if="message.role === 'assistant'" class="prose prose-sm max-w-none" v-html="renderMarkdown(message.content)"></div>
              <div v-else class="whitespace-pre-wrap">{{ message.content }}</div>
              <div class="text-xs mt-2 opacity-70">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="bg-white border-t border-gray-200 p-4">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div class="flex space-x-3">
            <textarea
              v-model="currentMessage"
              @keydown="handleKeydown"
              placeholder="输入您的问题... (Shift+Enter换行，Enter发送)"
              class="flex-1 resize-none border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              rows="2"
              :disabled="isLoading"
            ></textarea>
            <button
              @click="sendMessage"
              :disabled="!currentMessage.trim() || isLoading"
              class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- AI配置管理弹窗 -->
    <div v-if="showApiConfig" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-4xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold">AI配置管理</h3>
          <button
            @click="showApiConfig = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <!-- 当前配置状态 -->
        <div class="mb-6 p-4 bg-blue-50 rounded-lg">
          <h4 class="font-medium text-blue-900 mb-2">当前使用配置</h4>
          <div v-if="currentAiConfig" class="text-sm text-blue-800">
            <p><span class="font-medium">模型:</span> {{ currentAiConfig.model }}</p>
            <p><span class="font-medium">提供商:</span> {{ currentAiConfig.provider || 'siliconflow' }}</p>
            <p><span class="font-medium">API地址:</span> {{ currentAiConfig.apiUrl }}</p>
          </div>
          <div v-else class="text-sm text-blue-800">
            暂无配置
          </div>
        </div>
        
        <!-- 配置列表 -->
        <div class="mb-6">
          <div class="flex justify-between items-center mb-4">
            <h4 class="font-medium">配置列表</h4>
            <button
              @click="createNewConfig"
              class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
            >
              新建配置
            </button>
          </div>
          
          <div v-if="isLoadingConfig" class="text-center py-4">
            <div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
            <p class="mt-2 text-gray-600">加载中...</p>
          </div>
          
          <div v-else-if="aiConfigs.length === 0" class="text-center py-8 text-gray-500">
            暂无配置，请创建新配置
          </div>
          
          <div v-else class="space-y-3">
            <div
              v-for="config in aiConfigs"
              :key="config.id"
              class="border rounded-lg p-4 hover:bg-gray-50"
            >
              <div class="flex justify-between items-start">
                <div class="flex-1">
                  <div class="flex items-center gap-2 mb-2">
                    <h5 class="font-medium">{{ config.name }}</h5>
                    <span v-if="config.isDefault" class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">
                      默认
                    </span>
                  </div>
                  <p class="text-sm text-gray-600 mb-2">{{ config.description || '无描述' }}</p>
                  <div class="text-xs text-gray-500">
                    <span class="mr-4">模型: {{ config.model }}</span>
                    <span class="mr-4">提供商: {{ config.provider }}</span>
                    <span>创建时间: {{ config.createdAt ? new Date(config.createdAt).toLocaleString() : '未知' }}</span>
                  </div>
                </div>
                <div class="flex gap-2">
                  <button
                    v-if="!config.isDefault && config.id"
                    @click="setDefaultConfig(config.id!)"
                    class="px-3 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700"
                  >
                    设为默认
                  </button>
                  <button
                    @click="editConfig(config)"
                    class="px-3 py-1 text-xs bg-gray-600 text-white rounded hover:bg-gray-700"
                  >
                    编辑
                  </button>
                  <button
                    v-if="!config.isDefault && config.id"
                    @click="deleteConfig(config.id!)"
                    class="px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700"
                  >
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="flex justify-end">
          <button
            @click="showApiConfig = false"
            class="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
    
    <!-- AI配置表单弹窗 -->
    <div v-if="showConfigForm" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold">{{ editingConfigId ? '编辑配置' : '新建配置' }}</h3>
          <button
            @click="showConfigForm = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <form @submit.prevent="saveAiConfig" class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">配置名称 *</label>
              <input
                v-model="configForm.name"
                type="text"
                required
                placeholder="请输入配置名称"
                class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">提供商</label>
              <select
                v-model="configForm.provider"
                class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="siliconflow">硅基流动</option>
                <option value="openai">OpenAI</option>
                <option value="anthropic">Anthropic</option>
                <option value="other">其他</option>
              </select>
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">模型 *</label>
            <input
              v-model="configForm.model"
              type="text"
              required
              placeholder="例如: deepseek-ai/DeepSeek-V2.5"
              class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">API地址 *</label>
            <input
              v-model="configForm.apiUrl"
              type="url"
              required
              placeholder="https://api.siliconflow.cn/v1"
              class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">API密钥 *</label>
            <input
              v-model="configForm.apiKey"
              type="password"
              required
              placeholder="请输入API密钥"
              class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
            <textarea
              v-model="configForm.description"
              rows="3"
              placeholder="请输入配置描述（可选）"
              class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            ></textarea>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Temperature</label>
              <input
                v-model.number="configForm.parameters.temperature"
                type="number"
                min="0"
                max="2"
                step="0.1"
                class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Max Tokens</label>
              <input
                v-model.number="configForm.parameters.maxTokens"
                type="number"
                min="1"
                max="8000"
                class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
            </div>
          </div>
          
          <div class="flex justify-end space-x-3 pt-4">
            <button
              type="button"
              @click="showConfigForm = false"
              class="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="isLoadingConfig"
              class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {{ isLoadingConfig ? '保存中...' : '保存' }}
            </button>
          </div>
        </form>
      </div>
    </div>
    </div>
  </div>
</template>

<style scoped>
.prose {
  color: inherit;
}

.prose h1, .prose h2, .prose h3, .prose h4, .prose h5, .prose h6 {
  color: inherit;
  margin-top: 1em;
  margin-bottom: 0.5em;
}

.prose p {
  margin-bottom: 1em;
}

.prose code {
  background-color: #f3f4f6;
  padding: 0.125rem 0.25rem;
  border-radius: 0.25rem;
  font-size: 0.875em;
}

.prose pre {
  background-color: #1f2937;
  color: #f9fafb;
  padding: 1rem;
  border-radius: 0.5rem;
  overflow-x: auto;
  margin: 1em 0;
}

.prose pre code {
  background-color: transparent;
  padding: 0;
  color: inherit;
}

.prose ul, .prose ol {
  margin: 1em 0;
  padding-left: 1.5em;
}

.prose li {
  margin: 0.5em 0;
}

.prose blockquote {
  border-left: 4px solid #d1d5db;
  padding-left: 1rem;
  margin: 1em 0;
  font-style: italic;
}
</style>